import axios from "axios";
import { useUserStore } from "../stores";
let authorization = null;
/**
 *
 * @param {import("axios").AxiosRequestConfig} options 参数
 * @returns {JSON} 数据
 */
async function request(options) {
  try {
    const res = await axios({
      responseType: "json",
      ...options,
      headers: {
        ...options.headers,
        Authorization: authorization,
      },
    });

    const { data, headers } = res;

    if (data.status === 401) {
      localStorage.removeItem("token");
      window.location.href = "/auth";
    }
    if (headers.Authorization || headers.authorization) {
      authorization = headers.Authorization || headers.authorization;
      localStorage.setItem("token", authorization);
      const userStore = useUserStore();
      userStore.token = authorization;
    }

    return data;
  } catch (error) {
    console.error(error.response.status);
    if (error.response && error.response.status) {
      const { status } = error.response;
      if (status === 401) {
        localStorage.removeItem("token");
        window.location.href = "/auth";
      }
    }
  }
}
async function upload(url, filePath, name = "file") {
  const res = axios({
    url: url,
    header: {
      Authorization: authorization,
    },
    name,
  });
  return res.data;
}
// 设置请求头部，保存到本地的同时，也保存到 userStore
function setAuthorizationToken(token) {
  authorization = token;
}
export { setAuthorizationToken, upload };
export default request;
